import os
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class InputInt(QWidget):
    date_length_Signal = pyqtSignal(int)
    def __init__(self):
        super(InputInt, self).__init__()
        self.main_layout = QVBoxLayout()
        self.date_layout = QHBoxLayout()
        self.date_label = QLabel('数值:')
        self.date_length = QSpinBox()
        self.date_length.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.date_length.setRange(1, 365)  # 最多为365
        self.date_length.setValue(1)
        self.date_layout.addWidget(self.date_label)
        self.date_layout.addWidget(self.date_length)

        self.btn_layout = QHBoxLayout()
        self.OK_btn = QPushButton('确定')
        self.OK_btn.clicked.connect(self._setLength)
        self.No_btn = QPushButton('取消')
        self.No_btn.clicked.connect(self._closeWindow)
        self.btn_layout.addWidget(self.OK_btn)
        self.btn_layout.addWidget(self.No_btn)

        self.main_layout.addLayout(self.date_layout)
        self.main_layout.addLayout(self.btn_layout)

        self.setLayout(self.main_layout)

    def _setLength(self):
        value = self.date_length.value()
        self.date_length_Signal.emit(value)
        self.close()

    def _closeWindow(self):
        self.close()


class DifficutyInfo(QWidget):
    difficuty_Signal=pyqtSignal(str)
    def __init__(self):
        super(DifficutyInfo, self).__init__()

        self.setWindowTitle('设置难度')
        self.main_layout=QHBoxLayout()
        self.main_layout.setContentsMargins(20, 20, 20, 20)
        self.difficuty_label=QLabel('难度:')
        self.difficuty_edit=QLineEdit()
        self.btn=QPushButton('设置')
        self.btn.setShortcut(Qt.Key_Return)
        self.btn.setStyleSheet('QPushButton:hover{color:#FF8C00}')
        self.btn.clicked.connect(self._send_info)
        self.main_layout.addWidget(self.difficuty_label)
        self.main_layout.addWidget(self.difficuty_edit)
        self.main_layout.addWidget(self.btn)

        self.setLayout(self.main_layout)

    def _send_info(self):
        difficulty=self.difficuty_edit.text()
        self.difficuty_Signal.emit(difficulty)
        self.close()

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key()==Qt.Key_Enter:
            self._send_info()


class DifficultyTable(QTableWidget):

    def __init__(self,config_path,data):
        """
        难度列表: data= {'difficulty':['A','B','C','D'],'price':['1000','1000','1000','1000']}
        :param data:
        """
        super(DifficultyTable, self).__init__()
        self.CONFIG_PATH=config_path
        self.project_config_path=os.path.join(self.CONFIG_PATH,'project_config')
        self.data=data
        self.setShowGrid(True)
        self.init_table(self.data)
        self.verticalHeader().setDefaultSectionSize(50)
        self.verticalHeader().sectionDoubleClicked.connect(self.__v_set)
        self.horizontalHeader().setDefaultSectionSize(80)
        self.horizontalHeader().sectionDoubleClicked.connect(self.__h_set)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.rightMenu)
        self.setEditTriggers(QAbstractItemView.DoubleClicked)

    def rightMenu(self):
        mainMenu=QMenu()
        add_menu = QMenu('增减列')
        add_one_column_action=QAction('增加一列 Ctrl+→')
        add_one_column_action.triggered.connect(lambda:self._add_column(1))
        delete_one_column_action=QAction('减少一列  Ctrl+←')
        delete_one_column_action.triggered.connect(self._deleteLastColumn)
        add_menu.addAction(add_one_column_action)
        add_menu.addAction(delete_one_column_action)

        delete_menu=QMenu('删除')
        delete_row_action=QAction('删除所选行  Alt+R')
        delete_row_action.triggered.connect(self._deleteRows)
        delete_column_action=QAction('删除所选列')
        delete_column_action.triggered.connect(self._deleteColumns)
        # delete_menu.addAction(delete_row_action)
        delete_menu.addAction(delete_column_action)

        insert_menu=QMenu('插入')
        insert_row_action=QAction('行  R')
        insert_row_action.triggered.connect(self._insertRow)
        insert_column_action=QAction('插入列')
        insert_column_action.triggered.connect(self._insertColumn)
        # insert_menu.addAction(insert_row_action)
        insert_menu.addAction(insert_column_action)

        save_action=QAction('保存 Ctrl+S')
        save_action.triggered.connect(self._save_data)

        mainMenu.addMenu(add_menu)
        # mainMenu.addMenu(delete_menu)
        # mainMenu.addMenu(insert_menu)
        mainMenu.addAction(insert_column_action)
        mainMenu.addAction(delete_column_action)
        # mainMenu.addAction(save_action)
        mainMenu.exec_(QCursor.pos())


    def init_table(self,data):
        if data:
            print(data)
            difficulty_counts=len(self.data['difficulty'])
            self.setColumnCount(difficulty_counts)
            self.setHorizontalHeaderLabels(self.data['difficulty'])
            self.setRowCount(1)
            for c in range(self.columnCount()):
                item=QTableWidgetItem()
                text=data['price'][c]
                item.setText(text)
                item.setTextAlignment(Qt.AlignCenter)
                item.setBackground(QBrush(QColor('#F0FFFF')))
                self.setItem(0,c,item)

    def __v_set(self,index):
        """
        双击表头事件
        :param index:
        :return:
        """
        current_name = self.verticalHeaderItem(index).text() if self.verticalHeaderItem(index) else str(index + 1)
        self.difficuty_widow = DifficutyInfo(current_name)
        self.difficuty_widow.difficuty_Signal.connect(self._set_name)
        self.difficuty_widow.show()

    def __h_set(self,index):
        """
        双击表头事件
        :param index:
        :return:
        """
        self.difficulty_window=DifficutyInfo()
        self.difficulty_window.difficuty_Signal.connect(self._add_difficuty)
        self.difficulty_window.show()


    def _addDifficutyLevel(self):
        """
        设置难度
        :return:
        """
        self.difficulty_window=DifficutyInfo()
        self.difficulty_window.difficuty_Signal.connect(self._add_difficuty)
        self.difficulty_window.show()

    def _add_difficuty(self,difficuty):
        """
        为防止空信息表，生成一个新的item
        :param difficuty:
        :return:
        """
        if difficuty:
            c=self.currentColumn()
            item = QTableWidgetItem()
            item.setText(difficuty)
            self.setHorizontalHeaderItem(c, item)


    def _addColumns(self):
        """
        在最后添加列数
        :return:
        """
        self.int_window_c=InputInt()
        self.int_window_c.setWindowTitle('添加列')
        self.int_window_c.date_length_Signal.connect(self._add_column)
        self.int_window_c.show()
        print('增加列数')

    def _add_column(self,int_value):
        """
        槽函数,返回选择的数量.根据数量在尾后添加空列数,注意设置水平表头
        :param int_value:
        :return:
        """
        ori_count=self.columnCount()

        self.setColumnCount(ori_count+int_value)
        for c in range(ori_count, self.columnCount()):
            h_item=QTableWidgetItem()
            h_item.setText(str(ori_count+1))
            self.setHorizontalHeaderItem(c,h_item)
            for r in range(self.rowCount()):
                item=QTableWidgetItem()
                item.setText('')
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(r,c,item)

    def _deleteRows(self):
        """
        删除所选择行
        :return:
        """
        print('删除所选择行')
        s_items=self.selectedItems()
        if s_items:
            selected_rows=[]
            for i in s_items:
                row=i.row()
                if row not in selected_rows:
                    selected_rows.append(row)
            for r in range(len(sorted(selected_rows))):
                self.removeRow(selected_rows[r]-r)

    def _insertRow(self):
        """
        插入行,注意生成新行的时候，表头要设置值，否则保存为报错.新生的item也需要设置''值，否则为None
        :return:
        """
        r=self.currentRow()
        print('currentRow:',r)
        self.insertRow(r)
        # self.currentRow()
        item=QTableWidgetItem()
        item.setText(str(r+1))
        self.setVerticalHeaderItem(r,item)#初始化表头

        for c in range(self.columnCount()):#初始化item
            c_item=QTableWidgetItem()
            c_item.setText('')
            c_item.setBackground(QBrush(QColor('#F0FFFF')))
            c_item.setTextAlignment(Qt.AlignCenter)
            self.setItem(r,c,c_item)


    def _insertColumn(self):
        """
        插入列
        :return:
        """
        c=self.currentColumn()
        # print(r)
        self.insertColumn(c)
        # self.currentRow()
        item=QTableWidgetItem()
        item.setText(str(c+1))
        self.setHorizontalHeaderItem(c,item)#初始化表头

        for r in range(self.rowCount()):#初始化item
            r_item=QTableWidgetItem()
            r_item.setText('')
            r_item.setBackground(QBrush(QColor('#F0FFFF')))
            r_item.setTextAlignment(Qt.AlignCenter)
            self.setItem(r,c,r_item)



    def _deleteLastRow(self):
        """
        删除最后一行
        :return:
        """
        self.removeRow(self.rowCount()-1)

    def _deleteColumns(self):
        """
        删除所选择列
        :return:
        """
        print('删除所选择列')
        s_items=self.selectedItems()
        if s_items:
            selected_columns=[]
            for i in s_items:
                column=i.column()
                if column not in selected_columns:
                    selected_columns.append(column)
            # print('selected_columns:',selected_columns)
            for c in range(len(sorted(selected_columns))):
                self.removeColumn(selected_columns[c]-c)

    def _deleteLastColumn(self):
        """
        删除最后一列
        :return:
        """
        self.removeColumn(self.columnCount()-1)


    def _save_data(self):
        difficulty_list=[]
        price_list=[]
        for c in range(self.columnCount()):
            h_item=self.horizontalHeaderItem(c)
            difficulty=h_item.text()
            difficulty_list.append(difficulty)
            price_item=self.item(0,c)
            price=price_item.text()
            price_list.append(price)

        self.data['difficulty']=difficulty_list
        self.data['price']=price_list
        try:
            with open(self.project_config_path,'w',encoding='utf8') as w:
                w.write(str(self.data))
        except Exception as save_data_ERR:
            QMessageBox.information(self,'error',str(save_data_ERR))

    def get_data(self):
        difficulty_list=[]
        price_list=[]
        for c in range(self.columnCount()):
            h_item=self.horizontalHeaderItem(c)
            difficulty=h_item.text()
            difficulty_list.append(difficulty)
            price_item=self.item(0,c)
            price=price_item.text()
            price_list.append(price)

        self.data['difficulty']=difficulty_list
        self.data['price']=price_list
        return self.data

    def keyPressEvent(self, QKeyEvent):
        if QApplication.keyboardModifiers()==Qt.ControlModifier:
            if QKeyEvent.key()==Qt.Key_Right:
                self._add_column(1)
            if QKeyEvent.key() == Qt.Key_Left:
                self._deleteLastColumn()



#
class DifficultyWindow(QWidget):

    def __init__(self):
        super(DifficultyWindow, self).__init__()
        self.CONFIG_PATH=os.path.join(os.path.dirname(__file__),'config')
        self.project_config_path=os.path.join(self.CONFIG_PATH,'project_config')
        self.project_config_data = self.get_project_config(self.project_config_path)

        self.big_font=QFont('',25,65)
        self.setWindowTitle('镜头资产难度设置')
        self.setMinimumWidth(800)
        self.main_layout=QVBoxLayout()
        self.main_layout.setSpacing(25)
        self.shot_label_layout=QHBoxLayout()
        self.shot_label_layout.setAlignment(Qt.AlignCenter)
        self.shot_label=QLabel('镜头价格设置')
        self.shot_label.setFont(self.big_font)
        self.shot_label_layout.addWidget(self.shot_label)
        self.shot_difficulty_table=DifficultyTable(self.CONFIG_PATH,self.project_config_data['Shot'])

        self.asset_label_layout=QHBoxLayout()
        self.asset_label_layout.setAlignment(Qt.AlignCenter)
        self.asset_label=QLabel('资产价格设置')
        self.asset_label.setFont(self.big_font)
        self.asset_label_layout.addWidget(self.asset_label)
        self.asset_difficulty_table=DifficultyTable(self.CONFIG_PATH,self.project_config_data['Asset'])

        self.btn_layout=QHBoxLayout()
        self.save_btn=QPushButton('保存配置')
        self.save_btn.clicked.connect(self._save_data)
        self.save_btn.setMinimumHeight(50)
        self.btn_layout.addWidget(self.save_btn)


        self.main_layout.addLayout(self.shot_label_layout)
        self.main_layout.addWidget(self.shot_difficulty_table)
        self.main_layout.addLayout(self.asset_label_layout)
        self.main_layout.addWidget(self.asset_difficulty_table)
        self.main_layout.addLayout(self.btn_layout)
        self.setLayout(self.main_layout)




    def get_project_config(self,path):
        data={}
        with open(path,'r',encoding='utf8') as r:
            data=eval(r.read())
        return data

    def _save_data(self):
        shot_data=self.shot_difficulty_table.get_data()
        asset_data=self.asset_difficulty_table.get_data()
        print('shot_data:',shot_data)
        print('asset_data:', asset_data)
        save_data={'Shot':shot_data,'Asset':asset_data}
        try:
            with open(self.project_config_path,'w',encoding='utf8') as w:
                w.write(str(save_data))
            QMessageBox.information(self,'提示','保存成功,请重新打开软件')
        except Exception as save_data_ERR:
            QMessageBox.information(self,'error',str(save_data_ERR))


if __name__ == '__main__':
    app=QApplication(sys.argv)
    D=DifficultyWindow()
    D.show()
    sys.exit(app.exec_())